const articleService = require("@/server/article");
const { successData, sendCode, success } = require("@/utils/r/result");
const fs = require("fs");

const article = {
  async GetList(req, res) {
    successData(res, await articleService.GetList(req.query));
  },
  async UpdateTop(req, res) {
    const data = req.body;
    sendCode(res, await articleService.UpdateTop(data));
  },
  async GetInfo(req, res) {
    const id = req.params.id;
    successData(res, await articleService.GetInfo(id));
  },
  async SaveOrUpdate(req, res) {
    const id = req["user_info_id"];
    sendCode(res, await articleService.SaveOrUpdate(req.body, id));
  },
  async SoftDelete(req, res) {
    //软删除
    sendCode(
      res,
      await articleService.SoftDelete(req.body.ids, req.body.is_delete)
    );
  },
  async Delete(req, res) {
    const ids = req.body;
    sendCode(res, await articleService.Delete(ids));
  },
  async Import(req, res) {
    const user_id = req["user_info_id"];
    //multer插件将获取的文件信息绑定到req.file对象身上
    // originalname上传的文件名即后缀，去除后缀作为文章标题保存
    // path上传后文件的地址
    const { originalname, path } = req.file;
    let filename = originalname.split(".md")[0]; //乱码
    filename = Buffer.from(filename, "binary").toString("utf-8"); //解码
    const fileContent = fs.readFileSync(path, "utf-8");
    fs.unlinkSync(path); //删除临时文件
    await articleService.Import(filename, fileContent, user_id);
    success(res);
  },
};

module.exports = article;
